#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Python API for manipulating notify on renren
"""

__author__ = "LongFei Meng"
__copyright__ = "Copyright 2012-2013 Renren-inc"
__credits__ = ["Longfei Meng"]
__license__ = "MIT <http://www.opensource.org/licenses/mit-license.php>"
__version__ = "0.1"
__maintainer__ = "LongFei Meng"
__email__ = "AlphaPerfect[AT]gmail[DOT]com"
__status__ = "Development"""

import sys
import re
import time
import os
import getopt
import datetime

sys.path.append("/data/home/longfei.meng/work/ggcode/rralpha/python/")
from json import demjson
from db.mysql_helper import QueryRunner
from db.mysql_helper import *

#sys.path.append('/data/home/longfei.meng/soft/python/simplejson-2.6.0/build/lib.linux-x86_64-2.4/simplejson')
#import simplejson as json

sys.path.append('/data/xce')
sys.path.append('/data/xce/IcePy-3.3.0/python')
import traceback
import Ice

Ice.loadSlice(
  "-I/data/home/longfei.meng/work/main_project/trunk/UtilSlice/slice " 
  "-I/data/home/longfei.meng/work/main_project/trunk/OceSlice/slice --all " 
  "/data/home/longfei.meng/work/main_project/trunk/UtilSlice/slice/Util.ice "
  "/data/home/longfei.meng/work/main_project/trunk/OceSlice/slice/Notify.ice ")
from xce.notify import *

#product_locator = ("--Ice.Default.Locator=Notify/Locator:tcp -h NotifyRegistry "# " -p 14400")
product_locator = ("--Ice.Default.Locator=Notify/Locator:tcp -h "
                  " f0.xce.d.xiaonei.com -p 14400")
test_locator = ("--Ice.Default.Locator=Notify/Locator:tcp -h " 
               " f8.xce.d.xiaonei.com -p 14400")
trace_flag = "--Ice.Trace.Network=1"

def main():
  try:
    opt_list, arg_list = getopt.getopt(sys.argv[1:], "u:o:d")
  except getopt.GetoptError:
    print(str(err))
    usage()
    sys.exit('Invalid argument:%s' % (sys.argv, ))
  uid = "433553862"
  out_file_name = ""
  for opt, arg in opt_list:
    if opt == "-u":
      uid = str(arg)
    elif opt == "-d":
      del_flag = True 
    elif opt == "-o":
      out_file_name = str(arg)
    else:
      sys.exit('unhandled option')
  update_database_desc()
  get_database_config()
  try:
    #ic = Ice.initialize([test_locator, trace_flag])
    ic = Ice.initialize([product_locator, trace_flag])
    name = "M@NotifyDispatcher0"
    prx = NotifyDispatcherPrx.checkedCast(ic.stringToProxy(name))
  except:
    traceback.print_exc()
    status = 1
  db_info_parser = MessageCenterDbParser("database_desc.xml")
  info_dict = db_info_parser.get_msg_db_info_by_uid(uid)
  show_db_info(info_dict)
  qrunner = QueryRunner(info_dict["host"], 
      info_dict["user"], 
      info_dict["password"], 
      info_dict["database"], 
      (int)(info_dict["port"]),
      out_file_name)
  db_requests = qrunner.get_friend_request(uid)
  friend_request = {}
  for request in db_requests:
    print request
    try:
       #decoded_json = sjson.loads(line[4])
       decoded_json = demjson.decode(request[4])
    except:
      print "json err",line[0]
      continue
    print "decoded id:", decoded_json["id"]
    friend_request["from"] = str(request[7])
    friend_request["to"] = str(uid)
    friend_request["type"] = "256"
    friend_request["schema_id"] = "256"
    friend_request["owner"] = str(request[7])
    friend_request["time"] = str(request[6])
    friend_request["source"] = str(request[7])
    for key in decoded_json:
      if(isinstance(decoded_json[key],int)) or isinstance(decoded_json[key], 
            long) or isinstance(decoded_json[key],list):
        print "integer:", key , " value:", decoded_json[key]
        friend_request[str(key)] = str(decoded_json[key])
      else:
        friend_request[str(key)] = str(decoded_json[key].encode('utf-8'))
        if 'head' not in friend_request:
          friend_request['head'] = 'http://head.xiaonei.com/photos/0/0/men_main.gif'
    try:
      prx.dispatch(friend_request)
    except:
      print "dispatch error\n"
      traceback.print_exc()
      status = 1
      sys.exit()

if __name__ == "__main__":
  main()

